package com.tensquare.web.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by WF on 2020/4/6 14:50
 * 网关过滤器
 */
@Component
public class WebFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //1.得到请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //2.得到请求对象
        HttpServletRequest request = currentContext.getRequest();
        //3.得到请求头
        String header = request.getHeader("Authorization");
        //4.如果存在它，就放到当前网关的请求头中
        if(StringUtils.isNotBlank(header)){
            currentContext.addZuulRequestHeader("Authorization",header);
        }
        return null;
    }
}
